<?php
/**
 * Created by PhpStorm.
 * User: cephei
 * Date: 11/29/15
 * Time: 11:55 AM
 */

namespace Plugins\DBFilm;


use Core\PluginContainer;

class Plugin_DBFilm
{
    private $db;
    private $radarList = [];

    public function __construct()
    {
        $this->db = PluginContainer::getInstance()->singletonMake('database');
        $this->radarList = $this->db->get('select * from plg_dbfilm_radars');
        $cron = PluginContainer::getInstance()->make('cron');
        if(!empty($cron)){
            $cron->appendTask('dbfilm_fetchnew','Plugins\DBFilm\Plugin_DBFilm','fetchNewFilms',86400,6);
            $cron->appendTask('dbfilm_fetch','Plugins\DBFilm\Plugin_DBFilm','fetchFilm',18000);
        }
    }

    public function fetchNewFilms($score = 0)
    {
        $curl = PluginContainer::getInstance()->make('curl');
        $response = $curl->sendRequest('http://api.douban.com/v2/movie/in_theaters');
        $json = json_decode($response);
        $list = $json->subjects;
        foreach ($list as $item) {
            if ($item->rating->average >= $score) {
                if ($this->db->first("select count(1) as c from plg_dbfilm_films where doubanid='" . $item->id . "'")->c <= 0) {
                    $this->db->insert('plg_dbfilm_films', ["title" => $item->title, "origintilte" => $item->original_title,
                        "rate" => $item->rating->average, "genres" => implode(',', $item->genres),
                        "doubanid" => $item->id, "smallimage" => $item->images->small, "mediumimage" => $item->images->medium,
                        "largeimage" => $item->images->large, "isfetch" => 0]);
                }
            }
        }
        $curl->close();
    }

    public function calcSourceScore($item, $purpose)
    {
        $score = 10;
        if (strpos($item["name"], $purpose) === false)
            return -1;
        $standardList = $this->db->get("select * from plg_dbfilm_scorestandard");
        foreach ($standardList as $standard) {
            if (strpos(strtoupper($item["name"]), $standard->type) !== false)
                $score += $standard->score;
        }
        $score += $item->size / 1024 / 1024 / 1024;
        return $score;
    }

    public function fetchFilm()
    {
        $fetchList = $this->db->get('select * from plg_dbfilm_films where isfetch=0');
        $fetchedList = [];
        foreach ($fetchList as $item) {
            foreach ($this->radarList as $radar) {
                $radar = PluginContainer::getInstance()->make($radar->name);
                $resultList = $radar->search($item->title);
                $maxScore = 0;
                $finalItem = null;
                foreach ($resultList as $result) {
                    $score = $this->calcSourceScore($result, $item->title);
                    if ($score > $maxScore) {
                        if ($score < 11)
                            continue;
                        $maxScore = $score;
                        $finalItem = $result;
                    }
                }
                if (!empty($finalItem)) {
                    //TODO Add Downloader
                    $thunder = PluginContainer::getInstance()->singletonMake("thunder");
                    $taskId = $thunder->addTask($finalItem["url"], $finalItem["name"], "TDDOWNLOAD", "magnet", "", "");
                    if ($taskId !== false) {
                        $this->db->update('plg_dbfilm_films', ["isfetch" => 1, "taskid" => $taskId], "where doubanid='" . $item->doubanid . "'");
                        $fetchedList[] = ["doubanid" => $item->doubanid, "downloadurl" => $taskId];
                    }
                }
            }
        }

    }

    public function sendRemind($fetchedList)
    {
        $template = file_get_contents(ROOT_PATH.'/Storage/DBFilm/Templates/newfilm.tpl');
        $loopTemplate = '';
        $result='';
        if (preg_match('/@loop([\s\S]*?)@endloop/', $template, $arr)) {
            $loopTemplate = $arr[1];
        }
        foreach ($fetchedList as $item) {
            $curl = PluginContainer::getInstance()->make('curl');
            $response = $curl->sendRequest("http://api.douban.com/v2/movie/subject/".$item['doubanid']);
            $json = json_decode($response);
            $json->downloadurl = $item['downloadurl'];
            $singleMovie =$loopTemplate;
            preg_match_all('/{([a-zA_Z@]+?)}/', $loopTemplate, $arr);
            foreach ($arr[1] as $var) {
                if (strpos($var, "@") !== false) {
                    $split = explode('@', $var);
                    $object = $split[0];
                    $property = $split[1];
                    $singleMovie = str_replace("{{$var}}", $json->$object->$property, $singleMovie);
                } else
                    $singleMovie = str_replace("{{$var}}", $json->$var, $singleMovie);
            }
            preg_match_all('/\[([a-zA_Z@]+?)\]/', $loopTemplate, $arr);
            foreach ($arr[1] as $var) {
                if (strpos($var, "@") !== false) {
                    $split = explode('@', $var);
                    $object = $split[0];
                    $property = $split[1];
                    $replace = [];
                    foreach ($json->$object as $value) {
                        $replace[] = $value->$property;
                    }
                    $singleMovie = str_replace("[$var]", implode('/', $replace), $singleMovie);
                } else
                    $singleMovie = str_replace("[$var]", implode('/', $json->$var), $singleMovie);
            }
            $result .= $singleMovie;
        }
        $result = preg_replace('/@loop[\s\S]*?@endloop/',$result,$template);
        $deliver = PluginContainer::getInstance()->singletonMake('deliverhub');
        $deliver->sendMessage('mail',1,["title"=>"Jupiter DB Film Found ".count($fetchedList)." films","content"=>$result,"type"=>"HTML"]);
    }
}